﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.Core.Linq;
using MethodWorx.CMS.Membership;
using System.Data.Linq;
using System.Data.SqlClient;
using MethodWorx.Core.DomainModel;

namespace MethodWorx.CMS.Linq
{
    public class LinqUserRepository : LinqRepository<LinqUser, User>, IUserRepository
    {
        public LinqUserRepository(DataContext context)
            : base(context)
        {
        }

        public User FindByName(string username)
        {
            return this.source.FirstOrDefault(u => u.Username == username);
        }

        public IEnumerable<User> GetUsersByUserType(UserType userType)
        {
            return this.source.Where(u => u.UserType == userType);
        }




        public override void Insert(User entity)
        {
            var linqUser = entity as LinqUser;
            if(linqUser != null)
            {
                linqUser.AttributesStorage = linqUser.Attributes.Base64SerializeUsingXml();
            }
            base.Insert(entity);
        }

        public override void Update(User entity)
        {
            var linqUser = entity as LinqUser;
            if (linqUser != null)
            {
                linqUser.AttributesStorage = linqUser.Attributes.Base64SerializeUsingXml();
            }
            base.Update(entity);
        }



        public IEnumerable<string> GetAttributes(UserType userType)
        {
            return this.GetUsersByUserType(userType).SelectMany(u => u.Attributes.Keys).Distinct();
        }
    }
}
